import { RouteRecordRaw } from "vue-router";
import { defineStore } from "pinia";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import { listRoutes } from "@/api/menu";

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

/**
 * Use meta.role to determine if the current user has permission
 *
 * @param roles 用户角色集合
 * @param route 路由
 * @returns
 */
const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  if (route.meta && route.meta.roles) {
    //角色【超级管理员】拥有所有权限，忽略校验
    if (roles.includes("ROOT")) {
      return true;
    }
    return roles.some((role) => {
      if (route.meta?.roles !== undefined) {
        return (route.meta.roles as string[]).includes(role);
      }
    });
  }
  return false;
};

/**
 * 递归过滤有权限的异步(动态)路由
 *
 * @param routes 接口返回的异步(动态)路由
 * @param roles 用户角色集合
 * @returns 返回用户有权限的异步(动态)路由
 */
const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];

  routes.forEach((route) => {
    const tmpRoute = { ...route }; // ES6扩展运算符复制新对象

    // 判断用户(角色)是否有该路由的访问权限
    if (hasPermission(roles, tmpRoute)) {
      if (tmpRoute.component?.toString() == "Layout") {
        tmpRoute.component = Layout;
        console.log();
      } else {
        const component = modules[`../../views/${tmpRoute.component}.vue`];
        if (component) {
          tmpRoute.component = component;
        } else {
          tmpRoute.component = modules[`../../views/error-page/404.vue`];
        }
      }

      if (tmpRoute.children) {
        tmpRoute.children = filterAsyncRoutes(tmpRoute.children, roles);
      }

      asyncRoutes.push(tmpRoute);
    }
  });

  return asyncRoutes;
};

// setup
export const usePermissionStore = defineStore("permission", () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);

  // actions
  function setRoutes(newRoutes: RouteRecordRaw[]) {
    routes.value = constantRoutes.concat(newRoutes);
  }
  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes(roles: string[]) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
		
		const r={"code":"00000","data":[{"path":"/system","component":"Layout","redirect":"/system/user","meta":{"title":"系统管理","icon":"system","hidden":false,"roles":["ADMIN"],"keepAlive":true},"children":[{"path":"user","component":"system/user/index","name":"user","meta":{"title":"用户管理","icon":"user","hidden":false,"roles":["ADMIN"],"keepAlive":true}},{"path":"role","component":"system/role/index","name":"role","meta":{"title":"角色管理","icon":"role","hidden":false,"roles":["ADMIN"],"keepAlive":true}},{"path":"cmenu","component":"system/menu/index","name":"cmenu","meta":{"title":"菜单管理","icon":"menu","hidden":false,"roles":["ADMIN"],"keepAlive":true}},{"path":"dept","component":"system/dept/index","name":"dept","meta":{"title":"部门管理","icon":"tree","hidden":false,"roles":["ADMIN"],"keepAlive":true}},{"path":"dict","component":"system/dict/index","name":"dict","meta":{"title":"字典管理","icon":"dict","hidden":false,"roles":["ADMIN"],"keepAlive":true}}]},{"path":"/api","component":"Layout","meta":{"title":"接口","icon":"api","hidden":false,"roles":["ADMIN"],"keepAlive":true},"children":[{"path":"apidoc","component":"demo/apidoc","name":"apidoc","meta":{"title":"接口文档","icon":"api","hidden":false,"roles":["ADMIN"],"keepAlive":true}}]},{"path":"/external-link","component":"Layout","redirect":"noredirect","meta":{"title":"外部链接","icon":"link","hidden":false,"roles":["ADMIN"],"keepAlive":true},"children":[{"path":"https://www.cnblogs.com/haoxianrui/p/16090029.html","meta":{"title":"document","icon":"document","hidden":false,"roles":["ADMIN"],"keepAlive":true}}]},{"path":"/multi-level-menu","component":"Layout","redirect":"/nested/level1/level2","meta":{"title":"多级菜单","icon":"multi_level","hidden":false,"roles":["ADMIN"],"keepAlive":true},"children":[{"path":"nested_level1_index","component":"nested/level1/index","redirect":"/nested/level1/level2","meta":{"title":"菜单一级","icon":"","hidden":false,"roles":["ADMIN"],"keepAlive":true},"children":[{"path":"nested_level1_level2_index","component":"nested/level1/level2/index","redirect":"/nested/level1/level2/level3","meta":{"title":"菜单二级","icon":"","hidden":false,"roles":["ADMIN"],"keepAlive":true},"children":[{"path":"nested_level1_level2_level3_index1","component":"nested/level1/level2/level3/index1","name":"nested_level1_level2_level3_index1","meta":{"title":"菜单三级-1","icon":"","hidden":false,"roles":["ADMIN"],"keepAlive":true}},{"path":"nested_level1_level2_level3_index2","component":"nested/level1/level2/level3/index2","name":"nested_level1_level2_level3_index2","meta":{"title":"菜单三级-2","icon":"","hidden":false,"roles":["ADMIN"],"keepAlive":true}}]}]}]},{"path":"/demo","component":"Layout","meta":{"title":"组件封装","icon":"menu","hidden":false,"roles":["ADMIN"],"keepAlive":true},"children":[{"path":"wangEditor","component":"demo/wangEditor","name":"wangEditor","meta":{"title":"富文本编辑器","icon":"","hidden":false,"roles":["ADMIN"],"keepAlive":true}},{"path":"uploader","component":"demo/uploader","name":"uploader","meta":{"title":"上传组件","icon":"","hidden":false,"roles":["ADMIN"],"keepAlive":true}},{"path":"IconSelector","component":"demo/IconSelector","name":"IconSelector","meta":{"title":"图标选择器","icon":"","hidden":false,"roles":["ADMIN"],"keepAlive":true}}]}],"msg":"一切ok"}
		
			const accessedRoutes = filterAsyncRoutes(r.data, roles);
			setRoutes(accessedRoutes);
			resolve(accessedRoutes);
			
      // 接口获取所有路由
      // listRoutes()
      //   .then(({ data: asyncRoutes }) => {
      //     // 根据角色获取有访问权限的路由
      //     const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
      //     setRoutes(accessedRoutes);
      //     resolve(accessedRoutes);
      //   })
      //   .catch((error) => {
      //     reject(error);
      //   });
    });
  }
  return { routes, setRoutes, generateRoutes };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
